﻿using System;

namespace BitButterCORE.Extension
{
	static class PersistentExtension
	{
		public static int GetPayload(this byte[] data, out byte[] payload)
		{
			var result = default(byte[]);
			var lengthByteCount = sizeof(uint);
			if (data != null && data.Length > lengthByteCount)
			{
				var payloadLength = BitConverter.ToInt32(data, 0);
				if (data.Length >= lengthByteCount + payloadLength)
				{
					result = new byte[payloadLength];
					Array.Copy(data, lengthByteCount, result, 0, payloadLength);
				}
			}
			payload = result;
			return (result?.Length + lengthByteCount) ?? 0;
		}

		public static byte[] TruncateToEnd(this byte[] source, int start)
		{
			var result = default(byte[]);
			if (source != null && source.Length > start)
			{
				var truncateLength = source.Length - start;
				result = new byte[truncateLength];
				Array.Copy(source, start, result, 0, truncateLength);
			}
			return result;
		}

		public static byte[] PrependLength(this byte[] payload)
		{
			var result = default(byte[]);
			var length = payload?.Length ?? 0;
			if (length > 0)
			{
				var lengthBytes = BitConverter.GetBytes((uint)length);
				var lengthBytesSize = sizeof(uint);
				result = new byte[lengthBytesSize + length];
				Array.Copy(lengthBytes, result, lengthBytesSize);
				Array.Copy(payload, 0, result, lengthBytesSize, length);
			}
			return result;
		}

		public static byte[] Append(this byte[] target, byte[] source)
		{
			var result = target;
			if (target != null && source != null)
			{
				var totalLength = target.Length + source.Length;
				if (totalLength > 0)
				{
					result = new byte[totalLength];
					Array.Copy(target, result, target.Length);
					Array.Copy(source, 0, result, target.Length, source.Length);
				}
			}
			return result;
		}
	}
}
